package top.xylweb.login.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.xylweb.common.utils.SecurityUtils;
import top.xylweb.user.entity.User;
import top.xylweb.user.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping("login")
public class LoginController {


    @Autowired
    private UserService userService;

    /**
     * @Author X [**.**.**]
     * @Date 2017/12/17 15:23
     * Description 登录页面
     **/
    @RequestMapping
    public String login(){
        return "login";
    }



    /**
     * @Author X [**.**.**]
     * @Date 2017/12/17 15:19
     * Description 校验检查登录
     **/
    @RequestMapping("/check")
    @ResponseBody
    public String loginCheck(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //查询数据库   调用MD5进行加密  然后比较
        User user = userService.findUserBuUserName(username);
        if(user!=null){
            if(SecurityUtils.checkPassword(password,user.getPassword())){
                //登录成功   设置session
                request.getSession().setAttribute("userinfo",user);
                return "login_succ";
            }else{
                //登录失败
                return "login_fail";
            }
        }else{
            //登录失败
            return "login_fail";
        }
    }


    /**
     * @Author X [**.**.**]
     * @Date 2017/12/17 15:41
     * Description 创建用户
     **/
    @RequestMapping("/register")
    @ResponseBody
    public String register(@RequestBody User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        userService.createUser(user);
        return "succ";
    }



}
